package com.yubest.demo.anno.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yubest.demo.anno.Log;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 日志处理器
 * @Author hweiyu
 * @Description
 * @Date 2021/3/23 10:57
 */
@Slf4j
public class LogHandler implements Handler {

    @Override
    public void execute(Context context) {
        if (null == context.getMethod().getAnnotation(Log.class)) {
            return;
        }
        try {
            Map<String, Object> map = new HashMap<>();
            if (null != context.getArgNames()) {
                for (int i = 0; i < context.getArgNames().size(); i++) {
                    map.put(context.getArgNames().get(i), context.getArgValues().get(i));
                }
            }
            log.info("请求uri：{}, 方法：{}, 参数：{}", context.getUri(), context.getMethod().getName(), new ObjectMapper().writeValueAsString(map));
        } catch (JsonProcessingException e) {
            log.error("Json转换异常", e);
        }
    }
}
